﻿/*
ctl				input file控件id
subdir			存放子目录
onProgress		上传进度事件
onFinish		上传完成事件
*/
function Upload(ctl, subdir, onProgress, onFinish)
{
	ctl = document.getElementById(ctl);
	if (ctl == null)
	{
		if (onFinish != null) onFinish([]);
		return;
	}

	var files = [...ctl.files].filter(f => f.type.includes("image/"));
	if (files.length == 0)
	{
		if (onFinish != null) onFinish([]);
		return;
	}

	var total = 0, progress = 0;
	for (let f of files) total += f.size;

	var serverFiles = [], current = "";

	(function upload(index, offset)
	{
		var fd = new FormData();
		var file = files[index], end = offset + 500000, buffer = file.slice(offset, end);		//最大缓冲约500K一块
		if (file.name.split("").filter(c => new Set("~`!@#$%^&*+=").has(c)).length > 0)
		{
			alert(`文件名【${file.name}】包含无效字符，请改名后再上传`);
			return;
		}
		
		var dir = file.webkitRelativePath.substr(0, file.webkitRelativePath.length - file.name.length);

		fd.append(file.name.replace(/[\/\:]/gi, ""), buffer);
		fd.append("subdir", subdir);
		fd.append("odir", dir);

		if (offset > 0) fd.append("append", current);

		$.ajax(
			{
				url: "/web/handler/upload.ashx",
				type: "POST",
				data: fd,
				async: false,
				timeout: 10000,
				processData: false,
				contentType: false,
				success: path =>
				{
					progress += buffer.size;
					if (onProgress != null) onProgress(total, progress);

					current = path.split("|")[1];

					setTimeout(() =>
					{
						if (end < file.size - 1)
							upload(index, end);
						else
						{
							serverFiles.push(path);

							if (index < files.length - 1)
								upload(index + 1, 0);
							else if (onFinish != null)
								onFinish(serverFiles);
						}
					}, 0);
				}
			}
		).fail(() => upload(index, offset));
	})(0, 0);
}